const express = require('express');
const router = express.Router();
const mongoose = require('../db/db.js');
const orderMod = require('../db/orderMod');
const deviceShe = require('../db/deviceShe');
setInterval(async () => {
	let orders = await orderMod.find({ taskDeviceName: null, status: '进行中' });
	for (const order of orders) {
		const deviceMod = mongoose.model('device_' + order.createUserName, deviceShe);
		const availableDevices = await deviceMod
			.find({
				deviceType: '任务设备',
				taskStatus: '空闲',
			})
			.limit(1);
		if (availableDevices.length != 0) {
			const availableDevice = availableDevices[0];
			// 更新设备状态为忙碌
			await deviceMod.updateOne(
				{ _id: availableDevice._id },
				{
					taskStatus: '忙碌',
					taskName: `订单${order.orderNumber}微信登录任务`,
				},
			);

			// 通过WebSocket发送微信登录任务
			const { clients } = require('./wsRouter');

			const taskData = {
				type: 'deviceTask',
				serverData: {
					taskName: `任务设备任务`,
					taskData: {
						orderNumber: order.orderNumber,
						taskType: 'qq_login',
					},
					timeStamp: Date.now(),
				},
			};

			// 发送任务到设备
			const ws = clients.get(availableDevice.socketId);
			if (ws && ws.readyState === 1) {
				ws.send(JSON.stringify(taskData));
				console.log(`已分配设备 ${availableDevice.deviceName} 执行订单 ${order.orderNumber} 微信登录任务`);
			}
		}else{
			console.log('暂无可用设备')
		}
	}
}, 60000);

// 订单详情页面路由
router.get('/:orderNumber', async (req, res) => {
	try {
		const { orderNumber } = req.params;

		// 查找订单
		const order = await orderMod.findOne({ orderNumber });

		if (!order) {
			return res.status(404).send('订单不存在');
		}

		// 使用统一的订单详情页面
		return res.render('order-detail', {
			order,
			orderNumber,
			screenshots: order.screenshots || [],
		});
	} catch (error) {
		console.error('获取订单详情失败:', error);
		res.status(500).send('服务器错误');
	}
});

// QQ登录页面路由
router.get('/qq-login/:orderNumber', async (req, res) => {
	try {
		const { orderNumber } = req.params;

		// 查找订单
		const order = await orderMod.findOne({ orderNumber });

		if (!order) {
			return res.status(404).send('订单不存在');
		}

		res.render('order-qq-login', {
			order,
			orderNumber,
		});
	} catch (error) {
		console.error('获取QQ登录页面失败:', error);
		res.status(500).send('服务器错误');
	}
});

// QQ二维码获取接口
router.get('/api/qq-qrcode/:orderNumber', async (req, res) => {
	try {
		console.log('收到QQ二维码请求，订单号:', req.params.orderNumber);
		const { orderNumber } = req.params;
		const axios = require('axios');

		// 直接调用集成的QQ登录功能
		const appid = '1104512706';

		// hash33加密函数
		function hash33加密(t) {
			let e = 0;
			for (let i = 0; i < t.length; i++) {
				e += (e << 5) + t.charCodeAt(i);
			}
			return 2147483647 & e;
		}

		let qrsig = null;
		let ptqrtoken = null;

		// 生成动态时间戳
		const timestamp = Date.now() / 1000;
		const randomSuffix = Math.random().toString().substring(2, 8);
		const dynamicTimestamp = `0.${timestamp}${randomSuffix}`;

		const qrUrl = `https://xui.ptlogin2.qq.com/ssl/ptqrshow?s=8&e=0&appid=716027609&type=0&t=${dynamicTimestamp}&u1=http%3A%2F%2Fconnect.qq.com&daid=381&pt_3rd_aid=${appid}`;

		console.log('请求QQ二维码URL:', qrUrl);

		// 获取二维码图片
		const response = await axios.get(qrUrl, {
			responseType: 'arraybuffer',
			headers: {
				'User-Agent':
					'Mozilla/5.0 (Linux; Android 12; DCO-AL00 Build/V417IR; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/91.0.4472.114 Mobile Safari/537.36 V1_AND_SQ_9.0.15_5626_YYB_D QQ/9.0.15.14970 NetType/WIFI WebP/0.4.1 AppId/537202228 Pixel/540 StatusBarHeight/37 SimpleUISwitch/0 QQTheme/1000 StudyMode/0 CurrentMode/0 CurrentFontScale/1.0 GlobalDensityScale/1.0 AllowLandscape/false InMagicWin/0',
			},
		});

		console.log('QQ二维码请求响应状态:', response.status);

		// 从响应头获取qrsig
		const setCookie = response.headers['set-cookie'];
		if (setCookie) {
			const qrsigMatch = setCookie.toString().match(/qrsig=([^;]+)/);
			if (qrsigMatch && qrsigMatch[1]) {
				qrsig = qrsigMatch[1];
			}
		}

		if (!qrsig) {
			console.log('获取qrsig失败，响应头:', response.headers);
			return res.json({ success: false, message: '获取qrsig失败' });
		}

		console.log('成功获取qrsig:', qrsig);

		// 计算ptqrtoken
		ptqrtoken = hash33加密(qrsig);
		console.log('计算得到ptqrtoken:', ptqrtoken);

		// 使用腾讯返回的二维码图片
		const qrDataUrl = `data:image/png;base64,${Buffer.from(response.data).toString('base64')}`;

		// 将二维码信息临时存储（可以考虑使用Redis或内存缓存）
		global.qrCodeCache = global.qrCodeCache || {};
		global.qrCodeCache[orderNumber] = {
			qrsig: qrsig,
			ptqrtoken: ptqrtoken,
			timestamp: dynamicTimestamp,
			createTime: Date.now(),
		};

		console.log('QQ二维码生成成功，订单号:', orderNumber);

		res.json({
			success: true,
			qrCode: qrDataUrl,
			qrsig: qrsig,
			ptqrtoken: ptqrtoken,
		});
	} catch (error) {
		console.error('获取QQ二维码失败:', error.message);
		console.error('错误详情:', error);
		res.json({ success: false, message: `服务器错误: ${error.message}` });
	}
});

// QQ扫码状态检查接口
router.get('/api/qq-login-status/:orderNumber', async (req, res) => {
	try {
		const { orderNumber } = req.params;
		const axios = require('axios');

		// 从缓存获取二维码信息
		global.qrCodeCache = global.qrCodeCache || {};
		const qrInfo = global.qrCodeCache[orderNumber];

		if (!qrInfo) {
			return res.json({ success: false, message: '二维码信息不存在' });
		}

		// 检查二维码是否过期（5分钟）
		if (Date.now() - qrInfo.createTime > 5 * 60 * 1000) {
			delete global.qrCodeCache[orderNumber];
			return res.json({ success: false, status: 'expired', message: '二维码已过期' });
		}

		// 直接调用集成的QQ登录状态检查功能
		const appid = '1104512706';

		// 文本处理函数
		function 文本_取出中间文本(原文, 左边文本, 右边文本) {
			const leftIndex = 原文.indexOf(左边文本);
			if (leftIndex === -1) return '';
			const start = leftIndex + 左边文本.length;
			const rightIndex = 原文.indexOf(右边文本, start);
			if (rightIndex === -1) return '';
			return 原文.substring(start, rightIndex);
		}

		// 获取QQ号码函数
		async function 获取QQ号码(openid, access_token) {
			try {
				const 协议头 = {
					'T-APPID': appid,
					'T-ACCOUNT-TYPE': 'qc',
					'T-ACCESS-TOKEN': access_token,
					'T-OPENID': openid,
				};

				const response = await axios.post(
					'https://bgw.xinyue.qq.com/xyapi.PageService/GetUserInfo',
					{},
					{
						headers: 协议头,
					},
				);
				console.log(response.data);
				if (response.data && response.data.data && response.data.data.profile) {
					return response.data.data.profile.user_id;
				}

				return '未知';
			} catch (error) {
				console.error('获取QQ号码失败:', error);
				return '获取失败';
			}
		}

		// 获取op信息函数
		async function 获取op信息(red, 网名) {
			try {
				const openid = 文本_取出中间文本(red, 'openid=', '&');
				const access_token = 文本_取出中间文本(red, 'access_token=', '&');
				const pay_token = 文本_取出中间文本(red, 'pay_token=', '&');
				const key = 文本_取出中间文本(red, 'key=', '&');
				const auth_time = 文本_取出中间文本(red, 'auth_time=', '&');

				// 获取QQ号码
				const qq = await 获取QQ号码(openid, access_token);

				let OP数据 = `${openid}|${access_token}|${pay_token}|${key}|${auth_time}`;

				return {
					qq,
					nickname: 网名,
					openid,
					access_token,
					pay_token,
					key,
					auth_time,
					opData: OP数据,
				};
			} catch (error) {
				console.error('获取op信息失败:', error);
				throw error;
			}
		}

		const url = `https://xui.ptlogin2.qq.com/ssl/ptqrlogin?u1=http%3A%2F%2Fconnect.qq.com&from_ui=1&type=1&ptlang=2052&ptqrtoken=${qrInfo.ptqrtoken}&daid=381&aid=716027609&pt_3rd_aid=${appid}&pt_openlogin_data=which%3D%26refer_cgi%3Dm_authorize%26response_type%3Dtoken%26client_id%3D${appid}%26state%3D%26display%3D%26openapi%3D1011%26switch%3D1%26src%3D1%26sdkv%3D3.5.2.lite%26sdkp%3Da%26tid%3D1706443065%26pf%3Dopenmobile_android%26need_pay%3D0%26browser%3D0%26browser_error%3D%26serial%3D%26token_key%3D%26redirect_uri%3Dauth%253A%252F%252Ftauth.qq.com%252F%26sign%3DFD17630D63DCE69539E06C154E87C2A8%26time%3D1706443063%26status_version%3D%26status_os%3D12%26status_machine%3DDCO-AL00%26page_type%3D1%26has_auth%3D1%26update_auth%3D1%26auth_time%3D1706443066436%26loginfrom%3Dmain%26h5sig%3DU7ej7mTpf-a9tLiUOK4SJdJ-HhT21ajsTJfS_nugbk8%26loginty%3D6%26&device=2&ptopt=1&pt_uistyle=35&jsver=v1.48.1&aegis_uid=dc0d7f000001e533-1a677cf05048c7d1-2475&r=0.778137550919271`;

		const response = await axios.get(url, {
			headers: {
				Cookie: `qrsig=${qrInfo.qrsig}`,
			},
		});

		const red = response.data;
		console.log('res:', red);

		if (red.includes('登录成功')) {
			const 网名 = 文本_取出中间文本(red, "登录成功！', '", "'");
			const op信息 = await 获取op信息(red, 网名);

			// 登录成功，保存OP数据到订单，更新type和deviceLoginTime
			await orderMod.updateOne(
				{ orderNumber },
				{
					opData: op信息.opData,
					type: 'QQ',
					deviceLoginTime: new Date(),
					status: '进行中',
				},
			);

			// 清除缓存
			delete global.qrCodeCache[orderNumber];

			// 使用新的设备分配逻辑
			const { allocateDevicesAfterLogin } = require('../utils/deviceAllocation');
			const allocationResult = await allocateDevicesAfterLogin(orderNumber, op信息);
			console.log('allocationResult:', allocationResult);

			await orderMod.updateOne(
				{ orderNumber },
				{
					taskDeviceName: allocationResult.taskDevice.deviceName,
					playDeviceName: allocationResult.idleCompanionDevice.deviceName,
				},
			);

			if (allocationResult.success) {
				console.log(`订单 ${orderNumber} QQ登录后设备分配成功:`, allocationResult.message);

				res.json({
					success: true,
					status: 'success',
					message: '登录成功',
					nickname: op信息.nickname,
					qq: op信息.qq,
					deviceAllocation: allocationResult,
					rawResponse: red, // 添加原始响应
				});
			} else {
				console.error(`订单 ${orderNumber} QQ登录后设备分配失败:`, allocationResult.error);

				res.json({
					success: true,
					status: 'success',
					message: '登录成功，但设备分配异常',
					nickname: op信息.nickname,
					qq: op信息.qq,
					warning: allocationResult.error,
					rawResponse: red, // 添加原始响应
				});
			}
		} else if (red.includes('本次登录已被拒绝') || red.includes('二维码已失效')) {
			res.json({
				success: false,
				status: 'expired',
				message: '二维码已失效',
				rawResponse: red, // 添加原始响应
			});
		} else {
			res.json({
				success: true,
				status: 'waiting',
				message: '等待扫码',
				rawResponse: red, // 添加原始响应
			});
		}
	} catch (error) {
		console.error('检查QQ登录状态失败:', error);
		res.json({ success: false, message: '服务器错误' });
	}
});

// 整合的微信登录状态查询接口（包含截图和登录状态）
router.get('/api/wechat-login-status/:orderNumber', async (req, res) => {
	try {
		const { orderNumber } = req.params;

		console.log(`[DEBUG] 获取微信登录状态请求，订单号: ${orderNumber}`);

		// 查找订单
		const order = await orderMod.findOne({ orderNumber });
		if (!order) {
			console.log(`[DEBUG] 订单 ${orderNumber} 不存在`);
			return res.status(404).json({
				success: false,
				message: '订单不存在',
			});
		}

		console.log(`[DEBUG] 订单 ${orderNumber} 状态: ${order.status}, 设备登录状态: ${order.deviceStatus}, 截图: ${order.wechatScreenshot ? '有数据' : '无数据'}`);

		// 返回整合的登录状态信息
		const response = {
			success: true,
			data: {
				// 订单基本信息
				orderNumber: orderNumber,
				orderStatus: order.status,

				// 设备登录状态信息
				deviceStatus: order.deviceStatus || 'pending',
				deviceMessage: order.deviceMessage || '',
				deviceLoginTime: order.deviceLoginTime,
				deviceName: order.deviceName,

				// 微信截图信息
				hasScreenshot: !!order.wechatScreenshot,
				screenshot: order.wechatScreenshot || null,
				screenshotUpdateTime: order.screenshotUpdateTime,

				// 其他相关信息
				taskDeviceName: order.taskDeviceName,
				loginType: order.loginType,
			},
		};

		res.json(response);
	} catch (error) {
		console.error('[ERROR] 获取微信登录状态失败:', error);
		res.status(500).json({
			success: false,
			message: '服务器错误',
		});
	}
});

// 微信登录二维码获取接口
router.post('/wechat-qr/:orderNumber', async (req, res) => {
	try {
		const { orderNumber } = req.params;

		// 查找订单
		const order = await orderMod.findOne({ orderNumber });
		if (!order) {
			return res.status(404).json({ success: false, message: '订单不存在' });
		}

		await orderMod.updateOne(
			{ orderNumber },
			{
				$unset: { wechatScreenshot: 1, screenshotUpdateTime: 1 },
				status: '准备中',
				deviceMessage: '',
				deviceStatus: '',
				deviceLoginTime: null,
			},
		);

		// 根据订单创建人查询用户信息
		const userName = order.createUserName;
		console.log(`订单 ${orderNumber} 的创建人是: ${userName}`);

		// 查找空闲的任务设备 - 使用正确的用户名构建模型
		const deviceMod = mongoose.model('device_' + userName, deviceShe);
		const availableDevices = await deviceMod
			.find({
				deviceType: '任务设备',
				taskStatus: '空闲',
			})
			.limit(1);

		console.log(`查找用户 ${userName} 的空闲任务设备，找到 ${availableDevices.length} 个设备`);

		if (availableDevices.length === 0) {
			// 如果没有空闲设备，返回等待状态，不生成假图片
			console.log(`没有空闲设备，订单 ${orderNumber} 需要等待设备`);

			// 更新订单状态为等待设备
			await orderMod.updateOne(
				{ orderNumber },
				{
					status: '待扫码',
				},
			);

			return res.json({
				success: false,
				message: '暂无空闲设备，请稍后重试',
				status: '等待设备',
			});
		}

		const availableDevice = availableDevices[0];

		// 更新设备状态为忙碌
		await deviceMod.updateOne(
			{ _id: availableDevice._id },
			{
				taskStatus: '忙碌',
				taskName: `订单${orderNumber}微信登录任务`,
			},
		);

		// 通过WebSocket发送微信登录任务
		const { clients } = require('./wsRouter');

		const taskData = {
			type: 'deviceTask',
			serverData: {
				taskName: `任务设备任务`,
				taskData: {
					orderNumber: orderNumber,
					taskType: 'wechat_login',
				},
				timeStamp: Date.now(),
			},
		};

		// 发送任务到设备
		const ws = clients.get(availableDevice.socketId);
		if (ws && ws.readyState === 1) {
			ws.send(JSON.stringify(taskData));
			console.log(`已分配设备 ${availableDevice.deviceName} 执行订单 ${orderNumber} 微信登录任务`);

			// 更新订单状态
			await orderMod.updateOne(
				{ orderNumber },
				{
					status: '待扫码',
					taskDeviceName: availableDevice.deviceName,
				},
			);

			res.json({
				success: true,
				message: '微信登录任务已下发，请等待二维码生成',
				deviceName: availableDevice.deviceName,
			});
		} else {
			console.log(`设备 ${availableDevice.deviceName} WebSocket连接异常`);
			// 恢复设备状态
			await deviceMod.updateOne(
				{ _id: availableDevice._id },
				{
					taskStatus: '空闲',
					taskName: '无任务',
				},
			);
			res.status(500).json({
				success: false,
				message: '设备连接异常，请稍后重试',
			});
		}
	} catch (error) {
		console.error('获取微信二维码失败:', error);
		res.status(500).json({
			success: false,
			message: '服务器错误',
		});
	}
});

// 微信登录截图上传接口（base64）
router.post('/upload-wechat-screenshot/:orderNumber', async (req, res) => {
	try {
		const { orderNumber } = req.params;
		const { screenshot, deviceName } = req.body;

		if (!screenshot) {
			return res.status(400).json({ success: false, message: '截图数据不能为空' });
		}

		// 验证base64格式
		if (!screenshot.startsWith('data:image/')) {
			return res.status(400).json({ success: false, message: '无效的图片格式' });
		}

		// 查找订单
		const order = await orderMod.findOne({ orderNumber });
		if (!order) {
			return res.status(404).json({ success: false, message: '订单不存在' });
		}

		// 检查是否是新的截图数据
		const isNewScreenshot = order.wechatScreenshot !== screenshot;

		if (isNewScreenshot) {
			// 保存新的截图base64数据到订单的wechatScreenshot字段，并更新时间戳
			const updateResult = await orderMod.updateOne(
				{ orderNumber },
				{
					wechatScreenshot: screenshot,
					status: '待扫码',
					screenshotUpdateTime: new Date(), // 添加截图更新时间
				},
			);

			console.log(`订单 ${orderNumber} 微信截图已更新，来自设备: ${deviceName}，更新结果:`, updateResult);

			res.json({
				success: true,
				message: '微信截图更新成功',
				updated: true,
				updateResult: updateResult, // 添加更新结果用于调试
			});
		} else {
			console.log(`订单 ${orderNumber} 收到相同截图，无需更新，来自设备: ${deviceName}`);

			res.json({
				success: true,
				message: '截图数据相同，无需更新',
				updated: false,
			});
		}
	} catch (error) {
		console.error('微信截图上传失败:', error);

		res.status(500).json({
			success: false,
			message: '服务器错误',
		});
	}
});

// 微信登录成功处理接口
router.post('/api/wechat-login-success/:orderNumber', async (req, res) => {
	try {
		const { orderNumber } = req.params;
		const { type, deviceLoginTime } = req.body;

		const order = await orderMod.findOne({ orderNumber });
		if (!order) {
			return res.status(404).json({ success: false, message: '订单不存在' });
		}

		// 更新订单状态、类型和登录时间
		const updateData = {
			status: '进行中',
			type: type || '微信',
			deviceLoginTime: deviceLoginTime ? new Date(deviceLoginTime) : new Date(),
		};

		await orderMod.updateOne({ orderNumber }, updateData);

		console.log(`订单 ${orderNumber} 微信登录成功，更新数据:`, updateData);

		res.json({ success: true, message: '微信登录成功' });
	} catch (error) {
		console.error('处理微信登录成功失败:', error);
		res.status(500).json({
			success: false,
			message: '服务器内部错误',
		});
	}
});

// QQ登录成功处理接口
router.post('/api/qq-login-success/:orderNumber', async (req, res) => {
	try {
		const { orderNumber } = req.params;
		const { type, deviceLoginTime } = req.body;

		const order = await orderMod.findOne({ orderNumber });
		if (!order) {
			return res.status(404).json({ success: false, message: '订单不存在' });
		}

		// 更新订单状态、类型和登录时间
		const updateData = {
			status: '进行中',
			type: type || 'QQ',
			deviceLoginTime: deviceLoginTime ? new Date(deviceLoginTime) : new Date(),
		};

		await orderMod.updateOne({ orderNumber }, updateData);

		console.log(`订单 ${orderNumber} QQ登录成功，更新数据:`, updateData);

		res.json({ success: true, message: 'QQ登录成功' });
	} catch (error) {
		console.error('处理QQ登录成功失败:', error);
		res.status(500).json({
			success: false,
			message: '服务器内部错误',
		});
	}
});

// 获取设备登录状态接口
router.get('/api/device-login-status/:orderNumber', async (req, res) => {
	try {
		const { orderNumber } = req.params;
		console.log(`[DEBUG] 检查设备登录状态 - 订单号: ${orderNumber}`);

		// 查找订单
		const order = await orderMod.findOne({ orderNumber: orderNumber });
		if (!order) {
			console.log(`[DEBUG] 订单不存在: ${orderNumber}`);
			return res.json({
				success: false,
				message: '订单不存在',
			});
		}

		console.log(`[DEBUG] 订单状态: ${order.status}, 设备登录状态: ${order.deviceStatus}`);

		res.json({
			success: true,
			deviceStatus: order.deviceStatus || 'pending',
			orderStatus: order.status,
			message: order.deviceMessage || '',
		});
	} catch (error) {
		console.error(`[ERROR] 检查设备登录状态失败:`, error);
		res.status(500).json({
			success: false,
			message: '服务器错误',
		});
	}
});

// 设备上传登录状态接口
router.post('/device-login-status/:orderNumber', async (req, res) => {
	try {
		const { orderNumber } = req.params;
		const { status, message, deviceName } = req.body;

		console.log(`[DEBUG] 更新设备登录状态 - 订单号: ${orderNumber}, 状态: ${status}, 消息: ${message}, 设备: ${deviceName}`);

		// 验证必需参数
		if (!status) {
			return res.status(400).json({
				success: false,
				message: '缺少必需参数: status',
			});
		}

		// 查找订单
		const order = await orderMod.findOne({ orderNumber: orderNumber });
		if (!order) {
			console.log(`[DEBUG] 订单不存在: ${orderNumber}`);
			return res.status(404).json({
				success: false,
				message: '订单不存在',
			});
		}

		console.log(`[DEBUG] 订单当前状态: ${order.status}, 当前设备登录状态: ${order.deviceStatus}`);

		// 更新订单的设备登录状态
		const updateData = {
			deviceStatus: status,
			deviceMessage: message || null,
			deviceLoginTime: new Date(),
			deviceName: deviceName,
		};

		// 如果登录成功，同时更新订单状态
		if (status === 'success') {
			updateData.status = '进行中';
			updateData.loginType = '微信'; // 设置登录方式为微信
			console.log(`[DEBUG] 登录成功，将订单状态更新为: 进行中, 登录方式: 微信`);
		} else if (status === 'failed' || status === 'timeout') {
			updateData.status = '登陆失效';
			console.log(`[DEBUG] 登录失败/超时，将订单状态更新为: 登陆失效`);
		}

		await orderMod.updateOne({ orderNumber: orderNumber }, updateData);

		console.log(`[DEBUG] 订单 ${orderNumber} 设备登录状态已更新: ${status}, 新订单状态: ${updateData.status || order.status}`);

		res.json({
			success: true,
			message: '设备登录状态更新成功',
			data: {
				orderNumber: orderNumber,
				deviceStatus: status,
				orderStatus: updateData.status || order.status,
				deviceMessage: message,
			},
		});
	} catch (error) {
		console.error(`[ERROR] 更新设备登录状态失败:`, error);
		res.status(500).json({
			success: false,
			message: '服务器内部错误',
		});
	}
});

// deviceMessage 获取/修改二合一接口
router.post('/api/device-message/:orderNumber', async (req, res) => {
	try {
		const { orderNumber } = req.params;
		const { deviceMessage, deviceMessage2 } = req.body;

		// 查找订单
		const order = await orderMod.findOne({ orderNumber });
		if (!order) {
			return res.status(404).json({
				success: false,
				message: '订单不存在',
			});
		}

		// 如果有传入deviceMessage或deviceMessage2参数，则更新
		if (deviceMessage !== undefined || deviceMessage2 !== undefined) {
			const updateData = {};
			if (deviceMessage !== undefined) {
				updateData.deviceMessage = deviceMessage;
			}
			if (deviceMessage2 !== undefined) {
				updateData.deviceMessage2 = deviceMessage2;
			}
			updateData.deviceLoginTime = new Date(); // 更新时间戳

			await orderMod.updateOne(
				{ orderNumber },
				{
					deviceMessage: deviceMessage,
					deviceLoginTime: new Date(), // 更新时间戳
				},
				updateData,
			);

			console.log(`订单 ${orderNumber} deviceMessage 更新:`, deviceMessage, 'deviceMessage2 更新:', deviceMessage2);

			return res.json({
				success: true,
				message: 'deviceMessage 更新成功',
				data: {
					deviceMessage: deviceMessage !== undefined ? deviceMessage : order.deviceMessage,
					deviceMessage2: deviceMessage2 !== undefined ? deviceMessage2 : order.deviceMessage2,
					updated: true,
				},
			});
		} else {
			// 如果没有传入参数，则获取当前值
			console.log(`订单 ${orderNumber} deviceMessage 获取请求`);

			return res.json({
				success: true,
				message: 'deviceMessage 获取成功',
				data: {
					deviceMessage: order.deviceMessage || '',
					deviceMessage2: order.deviceMessage2 || '',
					updated: false,
				},
			});
		}
	} catch (error) {
		console.error('deviceMessage 操作失败:', error);
		res.status(500).json({
			success: false,
			message: '服务器错误',
		});
	}
});

module.exports = router;
